package org.example.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.exception.ServiceException;
import org.example.system.entity.TeacherEntity;
import org.example.system.mapper.TeacherMapper;
import org.example.system.service.TeacherService;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 教师服务实现
 */
@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 教师登录
     *
     * @param teacher
     * @return
     */
    @Override
    public String login(TeacherEntity teacher) {
        // 生成token（JwtUtil）
        String key = teacher.getId() + "," + teacher.getNumber() + "," + UUID.randomUUID().toString();
        String token = JwtUtil.createToken(key);
        // 把token放入redis缓存
        redisTemplate.opsForValue().set("LOGIN_TEACHER_TOKEN:" + key, token, 30, TimeUnit.MINUTES);
        // 返回token
        return token;
    }

    /**
     * 按条件分页查询
     *
     * @param teacher
     * @return
     */
    @Override
    public IPage<TeacherEntity> selectPage(TeacherEntity teacher) {
        LambdaQueryWrapper<TeacherEntity> wrapper = new LambdaQueryWrapper<>();
        // 条件
        if (StrUtil.isNotEmpty(teacher.getUsername())) {
            wrapper.like(TeacherEntity::getUsername, teacher.getUsername());    // 相似的姓名（模糊查询）
        }
        if (StrUtil.isNotEmpty(teacher.getNumber())) {
            wrapper.eq(TeacherEntity::getNumber, teacher.getNumber());    // 相同的工号（精确查询）
        }
        if (StrUtil.isNotEmpty(teacher.getProfessional())) {
            wrapper.eq(TeacherEntity::getProfessional, teacher.getProfessional());    // 相同的职称（精确查询）
        }
        if (StrUtil.isNotEmpty(teacher.getDegree())) {
            wrapper.eq(TeacherEntity::getDegree, teacher.getDegree());    // 相同的学历（精确查询）
        }
        if (StrUtil.isNotEmpty(teacher.getSex())) {
            wrapper.eq(TeacherEntity::getSex, teacher.getSex());    // 相同的性别（精确查询）
        }
        if (teacher.getBirthday() != null) {
            wrapper.eq(TeacherEntity::getBirthday, teacher.getBirthday());    // 相同的生日（精确查询）
        }
        if (StrUtil.isNotEmpty(teacher.getMobile())) {
            wrapper.like(TeacherEntity::getMobile, teacher.getMobile());    // 相似的联系电话（模糊查询）
        }
        if (StrUtil.isNotEmpty(teacher.getAddress())) {
            wrapper.like(TeacherEntity::getAddress, teacher.getAddress());    // 相似的家庭住址（模糊查询）
        }
        if (StrUtil.isNotEmpty(teacher.getEnable())) {
            wrapper.eq(TeacherEntity::getEnable, teacher.getEnable());    // 相同的启用状态（精确查询）
        }
        IPage<TeacherEntity> page = new Page<>();
        page.setCurrent(teacher.getPageNum());
        page.setSize(teacher.getPageSize());
        return teacherMapper.selectPage(page, wrapper);
    }

    /**
     * 添加教师
     *
     * @param teacher
     * @return
     */
    @Override
    public int add(TeacherEntity teacher) {
        // 用相同的工号去查数据库
        LambdaQueryWrapper<TeacherEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeacherEntity::getNumber, teacher.getNumber());   // 相同的工号
        List<TeacherEntity> existList = teacherMapper.selectList(wrapper);
        // 如果存在抛出一个自定义异常
        if (null != existList && existList.size() > 0) { // 证明存在相同的工号
            throw new ServiceException("工号已存在");
        }
        teacher.setPassword(DigestUtil.bcrypt(teacher.getPassword()));
        teacher.setCreateTime(new Date());
        return teacherMapper.insert(teacher);
    }

    /**
     * 修改
     *
     * @param teacher
     * @return
     */
    @Override
    public int update(TeacherEntity teacher) {
        // 用相同的工号去查数据库
        LambdaQueryWrapper<TeacherEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeacherEntity::getNumber, teacher.getNumber());
        List<TeacherEntity> existList = teacherMapper.selectList(wrapper);
        // 如果存在抛出一个自定义异常
        if (null != existList && existList.size() > 0) { // 证明存在相同的工号
            TeacherEntity existTeacher = existList.get(0);
            if (!existTeacher.getId().equals(teacher.getId())) {
                throw new ServiceException("工号已存在");
            }
        }
        // 如果匹配相同则不修改密码
        if (teacher.getPassword().equals(existList.get(0).getPassword()) && teacher.getPassword() != null) {
            teacher.setPassword(null);
        } else {
            teacher.setPassword(DigestUtil.bcrypt(teacher.getPassword()));
        }
        teacher.setUpdateTime(new Date());
        return teacherMapper.updateById(teacher);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(Long[] ids) {
        return teacherMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 根据id获取信息
     *
     * @param id
     * @return
     */
    @Override
    public TeacherEntity getOne(Long id) {
        return teacherMapper.selectById(id);
    }

    /**
     * 根据工号获取信息
     *
     * @param number
     * @return
     */
    @Override
    public TeacherEntity getOneByNumber(String number) {
        // 用相同的工号去查数据库
        LambdaQueryWrapper<TeacherEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeacherEntity::getNumber, number);
        List<TeacherEntity> existList = teacherMapper.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            return existList.get(0);
        }
        return null;
    }
}
